package com.kcwx.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.kcwx.common.annotation.Log;
import com.kcwx.common.constant.UserConstants;
import com.kcwx.common.core.controller.BaseController;
import com.kcwx.common.core.domain.AjaxResult;
import com.kcwx.common.core.page.TableDataInfo;
import com.kcwx.common.enums.BusinessType;
import com.kcwx.common.utils.poi.ExcelUtil;
import com.kcwx.system.domain.SysConfig;
import com.kcwx.system.service.ISysConfigService;

import com.kcwx.shareddomain.common.dto.DeleteDto;
import com.kcwx.shareddomain.common.dto.DelParaValid;
import com.kcwx.shareddomain.system.query.SysConfigQuery;
import com.kcwx.shareddomain.system.dto.SysConfigEditDto;
import com.kcwx.shareddomain.system.dto.ConfigSysTitleDto;
import com.kcwx.system.dtomap.SysConfigMap;

/**
 * 参数配置 信息操作处理
 * 
 */
@Api(tags = "系统管理-参数设置")
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController
{
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysConfigMap configMap;

    /**
     * 新增
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @Log(title = "新增参数配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysConfigEditDto dto)
    {
        SysConfig config=configMap.AddDtoToEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
        {
            return error("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setCreateBy(getUsername());
        int rowsAffect=configService.insertConfig(config);
        return rowsAffect>0?success():error("新增失败");
    }

    /**
     * 修改
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('system:config:edit')")
    @Log(title = "修改参数配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysConfigEditDto dto)
    {
        SysConfig config=configMap.EditDtoToEntity(dto);
        if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
        {
            return error("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setUpdateBy(getUsername());
        int rowsAffect=configService.updateConfig(config);
        return  rowsAffect>0?success():error("修改失败");
    }

    /**
     * 删除
     */
    @ApiOperation("删除参数配置")
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "删除参数配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(@RequestBody DeleteDto dto)
    {
        Long id=DelParaValid.validDel(dto);
        int rowsAffect=configService.deleteConfigById(id,getUsername());
        return rowsAffect>0? success():error("删除失败");
    }

    /**
     * 批量删除
     */
    @ApiOperation("批量删除参数配置")
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "批量删除参数配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/batchRemove")
    public AjaxResult batchRemove(@RequestBody DeleteDto dto)
    {
        Long []ids=DelParaValid.validBatchDel(dto);
        int rowsAffect=configService.deleteConfigByIds(ids,getUsername());
        return rowsAffect>0? success():error("删除失败");
    }
    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @PreAuthorize("@ss.hasPermi('system:config:list')")
    @Log(title = "参数配置分页查询", businessType = BusinessType.OTHER)
    @PostMapping("/list")
    public AjaxResult list(@RequestBody SysConfigQuery config)
    {
        startPage();
        List<SysConfig> list = configService.selectConfigList(config);
        return success(getDataTable(list));
    }

    /**
     * 根据id获取详细信息
     */
    @ApiOperation("根据id获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:config:query')")
    @Log(title = "根据id获取参数配置", businessType = BusinessType.OTHER)
    @GetMapping("/getById")
    public AjaxResult getInfo(Long id)
    {
        return success(configService.selectConfigById(id));
    }

    /**
     * 根据参数键名查询参数值
     */
    @ApiOperation("根据参数键名查询参数值")
    @Log(title = "根据参数键名查询参数值", businessType = BusinessType.OTHER)
    @GetMapping(value = "/configKey")
    public AjaxResult getConfigKey(String configKey)
    {
        return success(configService.selectConfigByKey(configKey));
    }
    /**
     * 刷新参数缓存
     */
    @ApiOperation("刷新参数缓存")
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "刷新参数缓存", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache()
    {
        configService.resetConfigCache();
        return success();
    }
    /**
     * 修改系统标题配置
     */
    @ApiOperation("修改系统标题")
    @PostMapping("/editSysTitle")
    public AjaxResult editSysTile(@RequestBody ConfigSysTitleDto dto) {
        String sysTitle=dto.getSysTitle();
        SysConfigQuery query=new SysConfigQuery();
        query.setConfigKey("sysTitle");
        List<SysConfig> list = configService.selectConfigList(query);
         int rowsAffect=0;
        if(!list.isEmpty()){
            SysConfig sysConfig=list.get(0);
            sysConfig.setConfigValue(sysTitle);
            sysConfig.setUpdateBy("admin");
            rowsAffect=configService.updateConfig(sysConfig);
        }
        else{
            SysConfig sysConfig=new SysConfig();
            sysConfig.setConfigKey("sysTitle");
            sysConfig.setConfigValue(sysTitle);
            sysConfig.setCreateBy("admin");
            rowsAffect=configService.insertConfig(sysConfig);
        }
        return rowsAffect>0?success():error("操作失败");
    }
    /**
     * 修改系统标题配置
     */
    @ApiOperation("获取系统标题配置")
    @GetMapping("/getSysTitle")
    public AjaxResult getSysTitle() {
        String title=configService.selectConfigByKey("sysTitle");
        Map<String,Object> titleData=new HashMap<String,Object>();
        titleData.put("sysTitle",title);
        return success(titleData);
    }
}
